/**
 * FileName: HandlerManager Author:   baoy Date:     2018/10/12 11:11 Description:
 */
package com.baoy.xxx.guava.serviceloader;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.Iterator;
import lombok.extern.slf4j.Slf4j;


/**
 * annotationhanlder 使用guava注解
 * 不用在META-INF/services/handler文件中添加全包路径
 */
@Slf4j
public enum HandlerManager {
    INSTANCE;

    private static List<Handler> list;

    static {
        list = new ArrayList<Handler>();
        ServiceLoader loader = ServiceLoader.load(Handler.class);
        Iterator it = loader.iterator();
        while (it.hasNext()) {
            list.add((Handler) it.next());
        }
    }

    public static HandlerManager addHandler(Handler handler) {
        list.add(handler);
        return INSTANCE;
    }

    public static void process() {
        for (Handler handler : list) {
            if (handler.accept()) {
                handler.handler();
            }
        }
    }


    public static void main(String[] arg) {
        HandlerManager.addHandler(new Handler() {
            @Override
            public boolean accept() {
                return true;
            }

            @Override
            public void handler() {
                log.info("-> i do eat ...");
            }
        }).process();
    }
}
